<template>
	<view class="content bgGray p16" style="min-height: 100%">
		<form @submit="onSubmit" class="bgWhite flex-r ver-c p16" style="border-radius: 20rpx">
			<view v-for="(item, index) in items" :key="index" class="flex-r mb16">
				<view style="width: 50%" class="flex-r ver-c fs14">
					<view class="gray">奖品{{ index + 1 }}：</view>
					<u-input
						class="f1"
						type="text"
						fontSize="12"
						placeholder="请输入奖品"
						v-model="item.tPrizename"
					></u-input>
				</view>
				<view style="width: 50%" class="flex-r ver-c fs14">
					<view class="gray pl16">概率：</view>
					<u-input
						v-model="item.tProbability"
						type="digit"
						fontSize="12"
						placeholder="请输入概率（0.01-100）"
						@input="(val) => handleInput(val, index)"
						@blur="validateProbability(index)"
					/>
					<text>%</text>
				</view>
			</view>
			<view class="fs13 gray mt16">剩余配置概率：{{ remainingPercentage }}%</view>
			<view class="fs13 red" v-if="totalProbability > 100">错误：总概率已超出100%！</view>
			<view class="fs13 gray">提示：1、中奖概率设置规则，区间0.01-100之间</view>
			<view class="fs13 gray">提示：2、需要满足所有奖品的中奖概率相加等于100</view>
			<view class="flex-r">
				<u-button type="info" customStyle="margin:32rpx 0" @click="addItem" text="添加奖品"></u-button>
				<view style="width: 30rpx"></view>
				<u-button type="info" customStyle="margin:32rpx 0" @click="resetItems" text="重置奖项"></u-button>
			</view>

			<u-button
				type="primary"
				class="mt16"
				:disabled="totalProbability !== 100 || totalProbability > 100"
				@click="onSubmit"
				text="提交"
			></u-button>
		</form>
	</view>
</template>

<script>
import Utils from '@/utils/utils.js'
import { setPrizeRule, getPrizeRule } from '@/api/mine.js'

export default {
	data() {
		return {
			tMerchantid: '',
			items: [{ tPrizename: '', tProbability: null }],
			totalProbability: 0,
			remainingPercentage: 100
		}
	},
	onLoad(option) {
		this.tMerchantid = option.tMerchantid
		this.fetchPrizeRules()
	},
	methods: {
		// 获取奖品规则
		async fetchPrizeRules() {
			try {
				const res = await getPrizeRule(this.tMerchantid)
				if (res.code === 200 && res.ruleList.length > 0) {
					this.items = res.ruleList.map((rule) => ({
						tPrizename: rule.tPrizename,
						tProbability: parseFloat(rule.tProbability)
					}))
					this.updateTotalProbability()
				}
			} catch (err) {
				console.error(err)
				Utils.toast('获取奖品规则失败，请稍后重试')
			}
		},
		// 添加新奖品
		addItem() {
			this.items.push({ tPrizename: '', tProbability: null })
		},
		// 重置奖项
		resetItems() {
			this.items = [{ tPrizename: '', tProbability: null }]
			this.totalProbability = 0
			this.remainingPercentage = 100
		},
		// 输入时实时校验
		handleInput(value, index) {
			// 过滤非法字符并更新值
			let filteredValue = value.replace(/[^0-9.]/g, '')
			if ((filteredValue.match(/\./g) || []).length > 1) {
				filteredValue = filteredValue.substring(0, filteredValue.lastIndexOf('.'))
			}
			this.$set(this.items[index], 'tProbability', filteredValue)
		},
		// 失焦时校验并格式化概率
		validateProbability(index) {
			let value = parseFloat(this.items[index].tProbability) || 0
			if (value > 100) value = 0
			else if (value < 0.01) value = 0.01
			this.$set(this.items[index], 'tProbability', value.toFixed(2))
			this.updateTotalProbability()
		},
		// 更新总概率
		updateTotalProbability() {
			this.totalProbability = this.items.reduce((sum, item) => sum + (parseFloat(item.tProbability) || 0), 0)
			this.remainingPercentage = (100 - this.totalProbability).toFixed(2)
			if (this.totalProbability > 100) Utils.toast('总概率不能超过100%')
		},
		// 提交表单
		async onSubmit() {
			if (!this.tMerchantid) return Utils.toast('登录过期，请重新登录')
			if (this.totalProbability !== 100) return Utils.toast('总概率必须等于100%')

			try {
				const data = this.items.map((item) => ({
					...item,
					tMerchantid: this.tMerchantid
				}))
				const res = await setPrizeRule(data)
				Utils.toast(res.msg)
				setTimeout(() => uni.navigateBack(), 2000)
			} catch (err) {
				console.error(err)
				Utils.toast('提交失败，请稍后重试')
			}
		}
	}
}
</script>
